package binaryTree;

/**
 * @author kunkun
 * @className LeetCode_226
 * @Description 翻转二叉树
 * @date 2025/3/13 11:39
 */
public class LeetCode_226 {

    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
    }

    public TreeNode invertTree(TreeNode root) {
        solution_1(root);
        return root;

    }

    //递归
    private void solution_1(TreeNode root) {
        //1. 无左无右
        if (root==null){
            return;
        }
        if ( root.left==null && root.right==null){
            return ;
        } else if (root.left!=null && root.right==null) {       //2. 有左无右
            root.right=root.left;
            root.left=null;
            solution_1(root.right);
        }else if (root.left==null && root.right!=null) {       //2. 无左有右
            root.left=root.right;
            root.right=null;
            solution_1(root.left);
        }else { //有左有右
            TreeNode temp = root.left;
            root.left = root.right;
            root.right=temp;
            solution_1(root.left);
            solution_1(root.right);

        }
    }
}
